﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Reflection;

namespace Invini.Training
{
    public class PropertyComponent : IPathComponent
    {
        public string PropertyName
        {
            get;
            set;
        }

        public IEnumerable<object> FindElements(object parentElement)
        {
            if (parentElement == null)
                return null;

            Type parentType = parentElement.GetType();

            PropertyInfo propertyInfo = parentType.GetProperty(this.PropertyName, BindingFlags.Public | BindingFlags.Instance);
            if(propertyInfo != null)
            {
                if (!propertyInfo.CanRead)
                    return null;

                return new object[] { propertyInfo.GetValue(parentElement) };
            }

            FieldInfo fieldInfo = parentType.GetField(this.PropertyName, BindingFlags.Public | BindingFlags.Instance);
            if (fieldInfo != null)
                return new object[] { fieldInfo.GetValue(parentElement) };

            return null;
        }
    }
}
